package com.bilibili.juc.tl;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

@Data
@AllArgsConstructor
class MyGCObject {
    String name = null;

    @Override
    protected void finalize() throws Throwable {
        //super.finalize();

        System.out.println("----invoke finalize method~!!!!!");

    }
}
public class GCDEmo {

    public static void main(String[] args) {
        //strongReference();
        //softReference();
        weakReference();

    }

    private static void strongReference() {
        MyGCObject object = new MyGCObject("何国金");
        System.out.println("gc before: "+object );

        object = null;

        //force System gc operation;
        System.gc();

        //sleep 500 毫秒
        try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }

        System.out.println("after  before: "+object );
    }

    private static void softReference()
    {
        //MyGCObject object2 = new MyGCObject("何国金");

        SoftReference<MyGCObject> softReference;
        softReference = new SoftReference<>(new MyGCObject("何国金"));
        //System.out.println("-----softReference:"+softReference.get());
        System.gc();
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("-----gc after内存够用: "+softReference.get());
        try
        {
            byte[] bytes = new byte[20 * 1024 * 1024];//20MB对象
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("-----gc after内存不够: "+softReference.get());
        }
    }
    private static void weakReference()
    {


        WeakReference<MyGCObject> weakReference;
        weakReference = new WeakReference<>(new MyGCObject("何国金"));
        //System.out.println("-----softReference:"+softReference.get());

        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("-----gc after内存够用: "+weakReference.get());

        System.gc();
        try
        {
            byte[] bytes = new byte[20 * 1024 * 1024];//20MB对象
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            System.out.println("-----gc after内存不够: "+weakReference.get());
        }
    }
}
